/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.map.MapUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.modules.system.domain.StudentWitnessConfig;
import me.zhengjie.modules.system.domain.StudentWitnessConfigRequest;
import me.zhengjie.modules.system.domain.StudentWitnessItemConfig;
import me.zhengjie.modules.system.repository.StudentWitnessConfigRepository;
import me.zhengjie.modules.system.service.StudentWitnessConfigService;
import me.zhengjie.modules.system.service.StudentWitnessItemConfigService;
import me.zhengjie.modules.system.service.dto.StudentWitnessConfigDto;
import me.zhengjie.modules.system.service.dto.StudentWitnessConfigQueryCriteria;
import me.zhengjie.modules.system.service.dto.StudentWitnessItemConfigDto;
import me.zhengjie.modules.system.service.dto.StudentWitnessItemConfigQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.StudentWitnessConfigMapper;
import me.zhengjie.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author 王宇
* @date 2023-10-25
**/
@Service
@RequiredArgsConstructor
public class StudentWitnessConfigServiceImpl implements StudentWitnessConfigService {

    private final StudentWitnessConfigRepository studentWitnessConfigRepository;
    private final StudentWitnessConfigMapper studentWitnessConfigMapper;

    @Autowired
    private StudentWitnessItemConfigService itemConfigService;

    @Override
    public Map<String,Object> queryAll(StudentWitnessConfigQueryCriteria criteria, Pageable pageable){
        Page<StudentWitnessConfig> page = studentWitnessConfigRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Map<String, Object> map = PageUtil.toPage(page.map(studentWitnessConfigMapper::toDto));
        if (MapUtil.isEmpty(map) || Objects.isNull(map.get("content"))) {
            return null;
        }
        List<StudentWitnessConfigDto> content = (List<StudentWitnessConfigDto>) map.get("content");
        content.forEach(s -> {
            StudentWitnessItemConfigQueryCriteria configQueryCriteria = new StudentWitnessItemConfigQueryCriteria();
            configQueryCriteria.setWitnessId(s.getWitnessId());
            List<StudentWitnessItemConfigDto> itemConfigDtoList = itemConfigService.queryAll(configQueryCriteria);
            if (CollectionUtils.isEmpty(itemConfigDtoList)){
                return;
            }
            s.setItemContent(itemConfigDtoList.get(0).getItemContent());
        });
        return map;
    }

    @Override
    public List<StudentWitnessConfigDto> queryAll(StudentWitnessConfigQueryCriteria criteria){
        return studentWitnessConfigMapper.toDto(studentWitnessConfigRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public StudentWitnessConfigDto findById(Long witnessId) {
        StudentWitnessConfig studentWitnessConfig = studentWitnessConfigRepository.findById(witnessId).orElseGet(StudentWitnessConfig::new);
        ValidationUtil.isNull(studentWitnessConfig.getWitnessId(),"StudentWitnessConfig","witnessId",witnessId);
        return studentWitnessConfigMapper.toDto(studentWitnessConfig);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StudentWitnessConfigDto create(StudentWitnessConfigRequest request) {
        StudentWitnessConfig resources = new StudentWitnessConfig();
        BeanUtils.copyProperties(request,resources);
        resources.setCreateby(SecurityUtils.getCurrentUsername());
        resources.setCreateTime(DateUtil.TimestampNow());
        resources.setWitnessStatus(ConstantUtils.Valid);
        resources.setUpdateTime(DateUtil.TimestampNow());
        resources.setUpdateby(SecurityUtils.getCurrentUsername());
        StudentWitnessConfigDto studentWitnessConfigDto = studentWitnessConfigMapper.toDto(studentWitnessConfigRepository.save(resources));
        if (!CollectionUtils.isEmpty(request.getItemList())){
            request.getItemList().stream().forEach(s -> {
                StudentWitnessItemConfig studentWitnessItemConfig = new StudentWitnessItemConfig();
                studentWitnessItemConfig.setWitnessId(studentWitnessConfigDto.getWitnessId());
                studentWitnessItemConfig.setItemContent(s);
                itemConfigService.create(studentWitnessItemConfig);
            });
        }
        return studentWitnessConfigDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(StudentWitnessConfigRequest request) {
        StudentWitnessConfig studentWitnessConfig = studentWitnessConfigRepository.findById(request.getWitnessId()).orElseGet(StudentWitnessConfig::new);
        ValidationUtil.isNull( studentWitnessConfig.getWitnessId(),"StudentWitnessConfig","id",request.getWitnessId());
        studentWitnessConfig.setWitnessStyle(request.getWitnessStyle());
        studentWitnessConfig.setWitnessType(request.getWitnessType());
        studentWitnessConfig.setTitle(request.getTitle());
        studentWitnessConfig.setUpdateTime(DateUtil.TimestampNow());
        studentWitnessConfig.setUpdateby(SecurityUtils.getCurrentUsername());
        studentWitnessConfigRepository.save(studentWitnessConfig);

        if (!CollectionUtils.isEmpty(request.getItemList())){
            StudentWitnessItemConfigQueryCriteria criteria = new StudentWitnessItemConfigQueryCriteria();
            criteria.setWitnessId(request.getWitnessId());
            List<StudentWitnessItemConfigDto> list = itemConfigService.queryAll(criteria);
            if (!CollectionUtils.isEmpty(list)){
                Long[] longs = list.stream().map(StudentWitnessItemConfigDto::getItemConfigId).collect(Collectors.toList()).stream().toArray(Long[]::new);
                itemConfigService.deleteAll(longs);
            }
            request.getItemList().stream().forEach(s -> {
                StudentWitnessItemConfig studentWitnessItemConfig = new StudentWitnessItemConfig();
                studentWitnessItemConfig.setWitnessId(request.getWitnessId());
                studentWitnessItemConfig.setItemContent(s);
                itemConfigService.create(studentWitnessItemConfig);
            });
        }
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long witnessId : ids) {
            studentWitnessConfigRepository.deleteById(witnessId);
        }
    }

    @Override
    public void download(List<StudentWitnessConfigDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StudentWitnessConfigDto studentWitnessConfig : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("见证类型，1课程感悟，2活力打call，3课程集锦", studentWitnessConfig.getWitnessType());
            map.put("标题", studentWitnessConfig.getTitle());
            map.put("样式类型，1：文本，2：视频，3：图片", studentWitnessConfig.getWitnessStyle());
            map.put("创建时间", studentWitnessConfig.getCreateTime());
            map.put(" createby",  studentWitnessConfig.getCreateby());
            map.put(" updateTime",  studentWitnessConfig.getUpdateTime());
            map.put(" updateby",  studentWitnessConfig.getUpdateby());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}